/*
 * ringbuffer.c
 *
 *  Created on: 2021年6月6日
 *      Author: wangbing
 *      Email : mz8023yt@163.com
 */

#ifdef __cplusplus
extern "C"
{
#endif

#include "ringbuffer_ex.h"
#include <stdio.h>              // printf
#include <stdint.h>             // uint8_t
#include <string.h>             // memcpy
#include <unistd.h>             // usleep

/**
 * @brief 队列初始化
 */
int ringbuffer_read_frame(RINGBUFFER *rbuf, HEADER *hbuf, uint8_t *obuf)
{
    int ret = -1;
    int wait_time = 10000;

    if(NULL == rbuf || NULL == hbuf || NULL == obuf)
    {
        return EINVAL;
    }

    memset(hbuf, 0, sizeof(HEADER));
    while(1)
    {
        /* 寻找同步码 */
        if(hbuf->sync[0] != SYNC0)
        {
            ret = ringbuffer_read(rbuf, (uint8_t *)&hbuf->sync[0], 1);
            if(ENODAT == ret)
            {
                // printf("."); fflush(stdout);
                usleep(wait_time);
                continue;
            }

            if(ret || hbuf->sync[0] != SYNC0)
            {
                memset(hbuf, 0, sizeof(HEADER));
                continue;
            }
        }

        if(hbuf->sync[1] != SYNC1)
        {
            ret = ringbuffer_read(rbuf, (uint8_t *)&hbuf->sync[1], 1);
            if(ENODAT == ret)
            {
                usleep(wait_time);
                continue;
            }

            if(ret || hbuf->sync[1] != SYNC1)
            {
                memset(hbuf, 0, sizeof(HEADER));
                continue;
            }
        }

        if(hbuf->sync[2] != SYNC2)
        {
            ret = ringbuffer_read(rbuf, (uint8_t *)&hbuf->sync[2], 1);
            if(ENODAT == ret)
            {
                usleep(wait_time);
                continue;
            }

            if(ret || hbuf->sync[2] != SYNC2)
            {
                memset(hbuf, 0, sizeof(HEADER));
                continue;
            }
        }

        if(hbuf->sync[3] != SYNC3)
        {
            ret = ringbuffer_read(rbuf, (uint8_t *)&hbuf->sync[3], 1);
            if(ENODAT == ret)
            {
                usleep(wait_time);
                continue;
            }

            if(ret || hbuf->sync[3] != SYNC3)
            {
                memset(hbuf, 0, sizeof(HEADER));
                continue;
            }
        }

        break;
    }

    ret = ringbuffer_read(rbuf, ((uint8_t *)hbuf) + 4, sizeof(HEADER) - 4);
    if(ret)
    {
        // printf("e");
        fflush(stdout);
        return ERR;
    }

    ret = ringbuffer_read(rbuf, obuf, hbuf->len);
    if(ret)
    {
        // printf("E");
        fflush(stdout);
        return ERR;
    }

    return 0;
}

#ifdef __cplusplus
}
#endif
